import { defineStore } from "pinia";
import { JxtechUser, JxtechLoginUser, UserDept } from "@/stores/interface/user";
import { useSysconfigrStore } from "@/stores/modules/sysconfig";
import { useTokenStore } from "@/stores/modules/token";
import { useAuthStore } from "@/stores/modules/auth";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { rsaencode } from "@/utils/rsa";
import { aesencode } from "@/utils/aes";
import { login, getUser, getSysConfig, getUserDept } from "@/api/modules/system/index";
import { disableToken } from "@/api/modules/org/disable-token";
import { getAccessToken } from "@/utils/common";
import { AxiosResponse } from "axios";
import { JxtechToken } from "@/stores/interface/token";
import { JxtechSysConfig } from "@/stores/interface/sysconfig";
import { PAGES_CONFIG } from "@/config/pages";
import router from "@/routers";
import pinia from "@/stores";

export const useUserStore = defineStore({
  id: "jxtech-user",
  state: (): JxtechUser => ({
    accountNonExpired: false,
    accountNonLocked: false,
    adminApp: [],
    credentialsNonExpired: false,
    deptCode: null,
    deptId: null,
    deptName: null,
    deptTreePath: null,
    enabled: false,
    orgId: null,
    orgName: null,
    orgTreePath: null,
    roles: [],
    stationId: null,
    stationName: null,
    subOrgCode: null,
    subOrgId: null,
    subOrgName: null,
    subOrgTreePath: null,
    telenantAdminOrg: false,

    userAccount: null,
    userAttributes: null,
    userDeptId: null,
    userFullName: null,
    userId: null,
    userImageUrl: null,
    userLevel: null,
    userType: null,
    userDeptList: []
  }),
  getters: {},
  actions: {
    /**登录 */
    login(loginUser: JxtechLoginUser) {
      const sysConfigState = useSysconfigrStore();
      let encodeLoginParams: JxtechLoginUser = { account: "", password: "" };
      if (useSysconfigrStore().encriptType === "rsa") {
        encodeLoginParams = rsaencode(loginUser.account, loginUser.password, sysConfigState.rsaPublicKey);
      } else if (useSysconfigrStore().encriptType === "aes") {
        // aes加密
        encodeLoginParams.account = aesencode(loginUser.account, sysConfigState.aeskey, sysConfigState.aesiv);
        encodeLoginParams.password = aesencode(loginUser.password, sysConfigState.aeskey, sysConfigState.aesiv);
      }
      if (loginUser.actionType && loginUser.actionType === "depart") {
        encodeLoginParams.account = loginUser.account;
        encodeLoginParams.password = loginUser.password;
      }
      return new Promise((resolve, reject) => {
        login(encodeLoginParams)
          .then((Response: AxiosResponse<JxtechToken>) => {
            resolve(Response);
          })
          .catch((Accident: AxiosResponse<any>) => {
            reject(Accident);
          });
      });
    },
    /**登出 */
    async logout() {
      try {
        const sysConfigState = useSysconfigrStore();
        /**调用退出登陆接口 */
        await disableToken(getAccessToken() as string);
        /**清空 tabs 数据 */
        useTabsStore().closeMultipleTab();
        /**清空 keepAlive 数据 */
        useKeepAliveStore().setKeepAliveName();
        /**清除token */
        useTokenStore().clearToken();
        /**清除人员信息 */
        this.clearUserInfo();
        /**清除部门列表 */
        this.clearUserDeptList();
        /**清除菜单 */
        useAuthStore().clearAuth();
        /**清除system信息 */
        sysConfigState.clearSysConfig();
        /**跳转logout页面 */
        router.push({ path: PAGES_CONFIG.LOGOUT_URL });
      } catch (error) {
        console.log(error);
      }
    },
    /**登录成功后处理 */
    loginSuccessAfter(responseData: JxtechToken) {
      const tokenState = useTokenStore();
      tokenState.setToken(responseData);
    },
    /**用户信息 */
    getInfo() {
      const sysConfigState = useSysconfigrStore();
      return new Promise(async (resolve, reject) => {
        try {
          if (!sysConfigState.appId) {
            /**系统信息接口 */
            const configData: AxiosResponse<JxtechSysConfig> = await getSysConfig();
            /**设置系统配置 */
            sysConfigState.setSysConfig(configData.data);
          }
          /**用户信息接口 */
          const userData: AxiosResponse<JxtechUser> = await getUser();
          /**设置用户信息 */
          this.setUserInfo(userData.data);
          /**userDeptList接口 */
          const deptList = await getUserDept();
          /**设置用户部门列表 */
          this.setUserDeptList(deptList.data);
          resolve(true);
        } catch (error) {
          reject(error);
        }
      });
    },
    /**设置用户信息 */
    setUserInfo(user: JxtechUser) {
      this.accountNonExpired = user.accountNonExpired;
      this.accountNonLocked = user.accountNonLocked;
      this.adminApp = user.adminApp;
      this.credentialsNonExpired = user.credentialsNonExpired;
      this.deptCode = user.deptCode;
      this.deptId = user.deptId;
      this.deptName = user.deptName;
      this.deptTreePath = user.deptTreePath;
      this.enabled = user.enabled;
      this.orgId = user.orgId;
      this.orgName = user.orgName;
      this.orgTreePath = user.orgTreePath;
      this.roles = user.roles;
      this.stationId = user.stationId;
      this.stationName = user.stationName;
      this.subOrgCode = user.subOrgCode;
      this.subOrgId = user.subOrgId;
      this.subOrgName = user.subOrgName;
      this.subOrgTreePath = user.subOrgTreePath;
      this.telenantAdminOrg = user.telenantAdminOrg;

      this.userAccount = user.userAccount;
      this.userAttributes = user.userAttributes;
      this.userDeptId = user.userDeptId;
      this.userFullName = user.userFullName;
      this.userId = user.userId;
      this.userImageUrl = user.userImageUrl;
      this.userLevel = user.userLevel;
      this.userType = user.userType;
    },
    /**清理用户信息 */
    clearUserInfo() {
      this.accountNonExpired = false;
      this.accountNonLocked = false;
      this.adminApp = [];
      this.credentialsNonExpired = false;
      this.deptCode = null;
      this.deptId = null;
      this.deptName = null;
      this.deptTreePath = null;
      this.enabled = false;
      this.orgId = null;
      this.orgName = null;
      this.orgTreePath = null;
      this.roles = [];
      this.stationId = null;
      this.stationName = null;
      this.subOrgCode = null;
      this.subOrgId = null;
      this.subOrgName = null;
      this.subOrgTreePath = null;
      this.telenantAdminOrg = false;
      this.userAccount = null;
      this.userAttributes = null;
      this.userDeptId = null;
      this.userFullName = null;
      this.userId = null;
      this.userImageUrl = null;
      this.userLevel = null;
      this.userType = null;
    },
    /**设置用户部门列表 */
    setUserDeptList(deptList: UserDept[]) {
      this.userDeptList = deptList;
    },
    /**清除用户部门列表 */
    clearUserDeptList() {
      this.userDeptList = [];
    }
  }
});
